import ms from 'ms';
import * as jwt from 'jsonwebtoken';
import { NormalObj } from '@/typings/global';

const generateProxy = (secret: string, data: NormalObj, expiresIn: string) => {
  return { token: jwt.sign(data, secret, { expiresIn }), expiresIn: ms(expiresIn) };
}

const generateAccessToken = (data: NormalObj) => {
  return generateProxy(process.env.ACCESS_TOEN_SECRET, data, '24h');
}

const generateRefreshToken = (data: NormalObj) => {
  return generateProxy(process.env.REFRESH_TOKEN_SECRET, data, '30 days');
}

/**
 * 生成Token
 * expiresIn 单位毫秒
*/
export const generateToken = (payload: NormalObj) => {
  const res1 = generateAccessToken(payload);
  const res2 = generateRefreshToken(payload);
  return {
    accessToken: res1.token,
    refreshToken: res2.token,
    expiresIn: res1.expiresIn
  }
}